package com.ice.body.hardware.controller;

import com.ice.base.result.ResponseResult;
import com.ice.base.result.AjaxResult;
import com.ice.base.util.*;
import com.ice.body.business.model.ReagentStock;
import com.ice.body.hardware.model.DeviceIo;
import com.ice.body.hardware.model.DeviceMachine;
import com.ice.body.hardware.model.DeviceWeigh;
import com.ice.body.hardware.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.*;

@RestController
@Slf4j
@Api( tags = "AAA-硬件控制器")
public class HardWareController {


    @Resource
    private IOUtil ioUtil;
    @Resource
    private DeviceIoService deviceIoService;
    @Resource
    private DeviceWeighService deviceWeighService;
    @Resource
    private DeviceMachineService machineService;
    @Resource
    private VoiceUtil voiceUtil;
    @Resource
    private RedisUtil redisUtil;


    /**
     * @param epcCode
     * @param weighType  1 出库 2归还
     * @param request
     * @return
     */
    @ApiOperation(value = "称重接口")
    @PostMapping("/api_p/weighForMix")
    public synchronized String weighForMix(@RequestParam("epcCode")String epcCode,@RequestParam("weighType") String weighType, HttpServletRequest request){

        String ipAddress = BaseUtil.getIPAddress(request);
        DeviceMachine machineModel = machineService.getByIp(ipAddress);
        if(null == machineModel){
            return "0";
        }
        String warehouseId = machineModel.getWarehouseId();
        String currentWeigh =  weigh(warehouseId);
        //根据IP查询哪个房间的称重 1 出库 2归还
        if("1".equals(weighType)){
            List<ReagentStock> ckList = (List<ReagentStock>) redisUtil.get(warehouseId+"ckList");// 出库列表信息
            if(ckList.size()>0){
                for (ReagentStock model: ckList) {
                    if(model.getEpcCode().equals(epcCode)){
                        model.setLeftWeigh(Double.parseDouble(currentWeigh));
                        break;
                    }
                }
                redisUtil.set(warehouseId + "ckList",ckList);
            }
        }else if("2".equals(weighType)){
            List<ReagentStock> ghList = (List<ReagentStock>) redisUtil.get(warehouseId+"ghList");// 归还列表信息
            if(ghList.size()>0){
                for (ReagentStock model: ghList) {
                    if(model.getEpcCode().equals(epcCode)){
                        model.setLeftWeigh(Double.parseDouble(currentWeigh));
                        break;
                    }
                }
                redisUtil.set(warehouseId + "ghList",ghList);
            }
        }
        return currentWeigh;

    }


    public  String weigh(String wareHouseId){
        DeviceWeigh weighModel = deviceWeighService.getByWareHouseId(wareHouseId);
        if(null == weighModel){
            return "0";
        }
        try{
            // 连接指示灯设备海尔35
            Socket socket = new Socket(InetAddress.getByName(weighModel.getIp()), Integer.parseInt(weighModel.getPort()));
            socket.setSoTimeout(3000);
            // 得到Socket连接的输出流
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            // 向服务器发送数据
            out.write(HexUtil.hex2Bytes("530D0A"));//S + 回车
            // 立刻发送数据
            out.flush();
            InputStream socketReader = socket.getInputStream();
            byte[] temp = new byte[37];
            int bytes = 0;
            String strOutput = "";
            String weigh = "";
            while(true){
                bytes = socketReader.read(temp);
                if(bytes ==0) {
                    continue;
                }
                strOutput += HexUtil.BinaryToHexString(temp);

                //把字符串中“ ”去掉
                strOutput = strOutput.replaceAll(" ", "");
                System.out.println("bytes="+bytes+"/ strOutput="+strOutput+"/  string="+HexUtil.fromHexString(strOutput));
                String result = HexUtil.fromHexString(strOutput);
                if(result.length() > 0){
                    result = result.replaceAll("S S","").replaceAll("g","").trim();
                }

                weigh = result;
                break;
            }
            out.close();
            socket.close();
            return weigh;
        } catch (IOException e) {
            log.info("调用称重模块异常~~~~~~");
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0";
    }




/*


    @ApiOperation(value = "方块RFID扫描开")
    @PostMapping("/api_p/openEpc")
    public Result<T> openFrid(){
        Result r = ResponseResult.success();
        try{
            rfidService.GClient_getEpcCode();
        }catch (Exception e){
            r = ResponseResult.error();
            e.printStackTrace();
        }
        return r;
    }

    @ApiOperation(value = "方块RFID扫描关")
    @PostMapping("/api_p/closeEpc")
    public Result<T> closeFrid() {
        Result r = ResponseResult.success();
        try{
            rfidService.GClient_stopReadEpc();
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();
        }
        return r;
    }




    //开启UHT的RFID扫描(白盒)
    @ApiOperation(value = "testWeight")
    @PostMapping("/api_p/testWeight")
    public void testWeight() {
        ThreadPoolExecutor threadPool = ThreadPoolUtil.getThreadPool();
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                try{
                    System.out.println("RFID线程:"+Thread.currentThread().getName());
                    // 创建串口必要参数接收类并赋值，赋值串口号，波特率，校验位，数据位，停止位
                    ParamConfig paramConfig = new ParamConfig("COM3", 9600, 0, 8, 1);
                    // 初始化设置,打开串口，开始监听读取串口数据
                    serialPort.init(paramConfig);
                }catch (Exception e){
                    e.printStackTrace();
                    serialPort.closeSerialPort();
                }
            }
        });
    }



    @ApiOperation(value = "UHT_白盒网口扫描开")
    @PostMapping("/api_p/UHT_netOpenRFID")
    public  Result<T>   UHT_netOpenRFID() {
        Result r = ResponseResult.success();
        try {
            rfidService.UHT_netOpenRFID();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            return r;
        }
    }

    @ApiOperation(value = "UHT_白盒网口扫描关")
    @PostMapping("/api_p/UHT_netCloseRFID")
    public Result<T>  UHT_netCloseRFID() {
        Result r = ResponseResult.success();
        try {
            rfidService.UHT_netCloseRFID();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            return r;
        }
    }


    @ApiOperation(value = "UHT_白盒扫描开-串口")
    @PostMapping("/api_p/UHT_openRFID")
    public void UHT_openRFID() {
        try {
            //多线程开启rfid
            rfidService.UHT_openRFID("COM3",115200);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "UHT_白盒扫描开-串口2")
    @PostMapping("/api_p/UHT_openRFID2")
    public void UHT_openRFID2() {
        try {
            //多线程开启rfid
            rfidService.UHT_openRFID("COM6",115200);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "UHT_白盒扫描关-串口")
    @PostMapping("/api_p/UHT_closeRFID")
    public void UHT_closeRFID() {
        try {
            //多线程开启rfid
            rfidService.UHT_closeRFID();
            System.out.println("关闭成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
*/




    @ApiOperation(value = "测试-进入实验室 开门 开灯 关门")
    @PostMapping("/api_p/openDoor")
    public AjaxResult<T> openDoor(HttpServletRequest request) {
        String ipAddress = BaseUtil.getIPAddress(request);
        AjaxResult r = ResponseResult.success();
        try{
        /*    DeviceIo ioModel = new DeviceIo();
            ioModel.setWarehouseId("1");
            ioModel.setSwitchType(1);
            ArrayList<DeviceIo> list = deviceIoService.selectListByModel(ioModel);

            String doorIp =list.get(0).getIp();
            String doorPort=list.get(0).getPort();

            list.forEach(io ->{
                ioUtil.operIo(io.getIp(),io.getPort(),io.getCommand());*/
          //  });
            voiceUtil.sendVoice("192.168.0.188","50002","啊实打实的");
            //延迟8秒关门
          //  Thread.sleep(8000);
            // 关闭IO模块1命令
        //    ioUtil.operIo(doorIp,doorPort,"CCDDA10100000001A346");
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();
        }
        return r;
    }

    @ApiOperation(value = "测试-走出实验室 先开门 在关门关灯")
    @PostMapping("/api_p/closeDoor1")
    public void closeDoor1() {
        try{
            DeviceIo ioModel = new DeviceIo();
            ioModel.setWarehouseId("1");
            ioModel.setSwitchType(2);

            ArrayList<DeviceIo> list = deviceIoService.selectListByModel(ioModel);
            String doorIp =list.get(0).getIp();
            String doorPort=list.get(0).getPort();
            // 开启IO模块1命令
            ioUtil.operIo(doorIp,doorPort,"CCDDA10100010001A448");
            //延迟8秒关门
            Thread.sleep(8000);
           // voiceUtil.sendVoice("","","再见");
            list.forEach(io ->{
                ioUtil.operIo(io.getIp(),io.getPort(),io.getCommand());
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "测试-根据房间开启IO")
    @PostMapping("/api_p/openDoor2")
    public void openDoor2(String wareHouseId) {
        try{
            List<DeviceIo> list = deviceIoService.getByWarehouseId(wareHouseId);
            list.forEach(a->{
                ioUtil.operIo(a.getIp(),a.getPort(),"CCDDA101FFFFFFFF9E3C");
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "测试-根据房间关闭IO")
    @PostMapping("/api_p/closeLight")
    public void closeLight(String wareHouseId) {
        try{

            List<DeviceIo> list = deviceIoService.getByWarehouseId(wareHouseId);
            list.forEach(a->{
                ioUtil.operIo(a.getIp(),a.getPort(),"CCDDA1010000FFFFA040");
            });

        }catch (Exception e){
            e.printStackTrace();
        }
    }






    @ApiOperation(value = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
    @PostMapping("/api_p/1232132321312")
    public void aaa(){
        try{
            //  close: FFEEEEEEEE
            ioUtil.operIo("192.168.100.7","8234","FFEEEEEEDD");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
